package xyz.zhangyi.onjava.java9.ecommerce.base;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class WebConnector {
    public String getPageContent(String webAddress) {
        URI httpURI = null;
        try {
            httpURI = new URI(webAddress);
            HttpRequest request = HttpRequest.newBuilder(httpURI).GET().build();

            CompletableFuture<HttpResponse<String>> futureResponse =
                    HttpClient.newHttpClient().sendAsync(request, HttpResponse.BodyHandlers.ofString());
            String responseBody = futureResponse.get(1, TimeUnit.SECONDS).body();

            System.out.println(responseBody);

            return HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString()).body();
        } catch (URISyntaxException | IOException | InterruptedException | ExecutionException | TimeoutException e) {
            e.printStackTrace();
            return "";
        }
    }
}
